import scrapy
import requests
from bid.items import BidItem
from bid.tools import *


class HunanSpider(scrapy.Spider):
    name = 'hunan'
    allowed_domains = ['ggzy.hunan.gov.cn']
    start_urls = ['https://ggzy.hunan.gov.cn/']
    t_lis = [
        ['https://ggzy.hunan.gov.cn/jydt/002002/002002001/002002001001/%s.html', '工程建设-招标公告','1'],
        ['https://ggzy.hunan.gov.cn/jydt/002002/002002001/002002001002/%s.html', '工程建设-中标候选人公示','2'],
        ['https://ggzy.hunan.gov.cn/jydt/002002/002002001/002002001003/%s.html', '工程建设-中标结果','3'],
        ['https://ggzy.hunan.gov.cn/jydt/002002/002002001/002002001004/%s.html', '工程建设-资质预审公告','2'],
        ['https://ggzy.hunan.gov.cn/jydt/002002/002002001/002002001005/%s.html', '工程建设-澄清与修改','2'],
        ['https://ggzy.hunan.gov.cn/jydt/002002/002002001/002002001006/%s.html', '工程建设-更正公告','2'],
        ['https://ggzy.hunan.gov.cn/jydt/002002/002002002/002002002001/%s.html', '政府采购-采购公告','1'],
        ['https://ggzy.hunan.gov.cn/jydt/002002/002002002/002002002002/%s.html', '政府采购-中标成交公告','3'],
        ['https://ggzy.hunan.gov.cn/jydt/002002/002002002/002002002003/%s.html', '政府采购-更正公告','2'],
    ]
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    msg = []
    def start_requests(self):
        for lis in self.t_lis:
            for page in range(1, 9999):
                if page==1:
                    res = requests.get(lis[0] % 'moreinfo', headers=self.headers)
                else:
                    res = requests.get(lis[0] % page, headers=self.headers)
                res.encoding = 'utf-8'
                ls = re.findall('<li class="wb-data-list clearfix">.*?href="(.*?)".*?title="(.*?)".*?wb-data-date">(.*?)<', res.text, re.S)
                if '404 Not Found' in res.text:
                    break
                for l in ls:
                    item = {}
                    item['link'] = 'https://ggzy.hunan.gov.cn' + l[0]
                    item['title'] = l[1]
                    item['time'] = l[2]
                    item['classification'] = '湖南-'+lis[1]
                    item['typ'] = lis[-1]
                    if redis_dupefilter(item) or item['time'].startswith('2021'):
                        self.msg.append(lis)
                        break
                    yield scrapy.Request(url=item['link'], callback=self.parse, meta={'item': item})
                if lis in self.msg:
                    print(lis[1],'完成')
                    break
                time.sleep(len(ls))

    def parse(self, response):
        item = BidItem()
        item.update(response.meta['item'])
        item['content'] = get_content(response.text, '//div[@class="news-article-para"]|//div[@class="news-article"]')
        item['content'] = re.sub('<div>【发稿时间.*?</div>|<div><div><div>报名中.*?</table></div></div>','',item['content'])
        item = get_field(dict(item))
        yield item
